// stores/counter.js
import { defineStore } from 'pinia';
import auth from "@/utils/auth.js";
import apis from "@/apis/index.js";
import utils from "@/utils/utils";
import atlas from "@/utils/atlas.js";//地图相关方法
import config from "@/config/index.js";

//im SDK
// IM 能力，包括单聊、群聊、通讯录等

// #ifdef MP-WEIXIN 
import NIM from 'nim-web-sdk-ng/dist/NIM_UNIAPP_SDK'
// #endif

// #ifdef H5
import NIM from 'nim-web-sdk-ng'
// #endif



const useCounterStore = defineStore('nim', {
  state: () => ({
    nim: null,
    msgUpdate: {},//消息更新
    limit: 100,
    updateSession: {},//会话更新
    sessions: [],//会话列表
  }),

  getters: {

  },

  actions: {
    async initIm() {
      //if (!dgdzParams.userInfo.id) return
      let { account, wangYiToken } = await apis.getIMinfo()

      if (this.nim) await this.nim.destroy()

      // 0.11.0 版开始支持单例模式获取实例, 在此之前通过 new 创建实例
      this.nim = NIM.getInstance(
        {
          debugLevel: 'off',
          appkey: '8e80abad3e9958bdba339e43551f1957',
          account: account,
          token: wangYiToken
        }, {}
      )
      const eventList = [
        'logined', 'multiPortLogin', 'kicked', 'willReconnect', 'disconnect',
        'msg', 'syncdone', 'proxyMsg', 'syncRoamingMsgs', 'syncOfflineMsgs',
        'syncMyNameCard', 'syncdone', 'sessions', 'updateMyNameCard', 'updateBlackList', 'updateMuteList',
        'sysMsg', 'syncSysMsgs', 'syncFriend', 'friends', 'users', 'updateSystemMessages', 'sysMsgUnread', 'pushEvents',
        'teamMsgReceipts', 'updateSession',
        'teams',
        'createTeam',
        'updateTeamMember',
        'updateTeam', 'addTeamMembers', 'updateTeamManagers', 'transferTeam', 'removeTeamMembers', 'dismissTeam', 'updateTeamMembersMute',
      ]
      eventList.forEach((key: any) => {
        this.nim.on(key, (res) => {
          console.log(`Receive ${key} event：`, res ? JSON.parse(JSON.stringify(res)) : res);
          //收到最新的消息
          if (key == 'msg') this.msgUpdate = res ? JSON.parse(JSON.stringify(res)) : res
          if (key == 'updateSession') this.updateSession = res ? JSON.parse(JSON.stringify(res)) : res
          if (key == 'sessions') this.sessions = res ? JSON.parse(JSON.stringify(res)) : res
        });
      })

      // then，receive event 'logined'
      console.log("是否登录状态", this.nim.status);
      if (this.nim.status == 'unconnected') await this.nim.connect();
    },

    //获取好友列表
    async getUsersNameCardFromServer(accounts) {
      if (!this.nim) await this.initIm()
      return await this.nim.user.getUsersNameCardFromServer({
        accounts
      })
    },

    //获取历史消息
    async getHistoryMsgs(to, endTime) {
      to = to.toString()
      if (!this.nim) await this.initIm()
      return await this.nim.msgLog.getHistoryMsgs({
        scene: 'p2p',
        to,
        limit: this.limit,
        asc: true,// 返回的结果按时间降序排列
        beginTime: 0,
        endTime,
        //reverse: false,// 从endTime开始往前查找
      })
    },

    //发送消息
    async sendMsg(to, body) {
      to = to.toString()
      if (!this.nim) await this.initIm()
      return await this.nim.msg.sendTextMsg({
        scene: 'p2p',
        to: to.toString(),
        body,
      })
    },

    //发送音频
    async sendAudioMsg(to, file) {
      to = to.toString()
      if (!this.nim) await this.initIm()
      //先上传音频
      return await this.nim.msg.sendAudioMsg({
        scene: 'p2p',
        to,
        filePath: file,
        "onUploadStart": function (task) { console.log('Upload start!', task) },
        "onUploadProgress": function (progress) { console.log('Uploading!', progress) },
        "onUploadDone": function (file) { console.log('Upload done!', file) },
        "onSendBefore": function (msg) { console.log('Get msg before send', msg) }
      })
    },

    //发送图片
    sendImageMsg(to, file) {
      to = to.toString()
      return new Promise((resolve, reject) => {
        this.nim.msg.sendImageMsg({
          "scene": "p2p",
          "to": to,
          filePath: file,
          // "onUploadStart": function (task) { console.log('Upload start!', task) },
          // "onUploadProgress": function (progress) { console.log('Uploading!', progress) },
          // "onUploadDone": function (file) { console.log('Upload done!', file) },
          "onSendBefore": function (msg) {
            resolve(msg)
          }
        })
      })
    },

    //发送位置
    async sendGeoLocationMsg(to, attach) {
      to = to.toString()
      return await this.nim.msg.sendGeoLocationMsg({
        "scene": "p2p",
        to,
        attach
      })
    },

    //发送自定义消息
    async sendCustomMsg(to, attach) {
      to = to.toString()
      return await this.nim.msg.sendCustomMsg({
        "scene": "p2p",
        to,
        attach
      })
    },

    //获取会话
    async getSessions() {
      if (!this.nim) await this.initIm()
      return await this.nim.session.getAllSessions()
    },

    //已读回执
    async sendMsgReceipt(msg) {
      if (!this.nim) await this.initIm()
      return await this.nim.msg.sendMsgReceipt({ msg })
    },

    //清理未读
    async resetSessionUnreadCount(id) {
      if (!this.nim) await this.initIm()
      return await this.nim.session.resetSessionUnreadCount({ id })
    }
  },
});

export default useCounterStore
